package com.hefei.garden.config.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefei.garden.config.spring.SpringUtil;
import com.hefei.garden.config.websocket.pojo.MessageCarrier;
import lombok.SneakyThrows;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * @author: devil
 * @Date: 2022/7/30 15
 * @Description:
 */
@Component
public class WebsocketMessageListener implements MessageListener {

    private final StringRedisTemplate redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);

    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] pattern) {
        ObjectMapper jackson = new ObjectMapper();
        MessageCarrier messageCarrier = jackson.readValue(message.toString(), MessageCarrier.class);
        String toSessionId = redisTemplate.opsForValue().get(messageCarrier.getToUser());
        WebSocketSession webSocketSession = WebSocketHandler.sessionMap.get(toSessionId);
        if (webSocketSession != null && webSocketSession.isOpen()) {
            webSocketSession.sendMessage(new TextMessage(messageCarrier.getContent()));
        }
    }
}
